package com.weather.androidweather.service;

import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.weather.androidweather.R;
import com.weather.androidweather.model.DayForecast;
import com.weather.androidweather.model.WeatherData;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherService {
    private static final String TAG = "WeatherService";
    private static final String API_KEY = "a8d517e4476022233d4d25938edd8eab";
    private static final String BASE_URL = "http://apis.juhe.cn/simpleWeather/query";
    
    private final OkHttpClient client;
    private final Gson gson;
    private final Context context;
    private WeatherData currentWeatherData;

    public WeatherService(Context context) {
        client = new OkHttpClient();
        gson = new Gson();
        this.context = context;
    }

    public interface WeatherCallback {
        void onSuccess(WeatherData weatherData);
        void onError(String message);
    }

    public void getWeatherByCity(String cityName, WeatherCallback callback) {
        String url = String.format("%s?key=%s&city=%s", BASE_URL, API_KEY, cityName);
        
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onError("网络请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.onError("服务器响应错误: " + response.code());
                    return;
                }

                try {
                    String jsonData = response.body().string();
                    JsonObject json = gson.fromJson(jsonData, JsonObject.class);
                    
                    parseWeatherData(json);
                    
                    callback.onSuccess(currentWeatherData);
                } catch (Exception e) {
                    callback.onError("数据解析错误: " + e.getMessage());
                }
            }
        });
    }

    private void parseWeatherData(JsonObject json) {
        if (json.get("error_code").getAsInt() == 0) {
            JsonObject result = json.getAsJsonObject("result");
            JsonObject realtime = result.getAsJsonObject("realtime");
            
            currentWeatherData = new WeatherData();
            currentWeatherData.setCityName(result.get("city").getAsString());
            currentWeatherData.setTemperature(Double.parseDouble(realtime.get("temperature").getAsString()));
            currentWeatherData.setHumidity(Integer.parseInt(realtime.get("humidity").getAsString()));
            currentWeatherData.setWeatherCondition(realtime.get("info").getAsString());
            currentWeatherData.setWindDirection(realtime.get("direct").getAsString());
            currentWeatherData.setWindPower(realtime.get("power").getAsString());
            currentWeatherData.setAqi(realtime.get("aqi").getAsString());
            
            // 添加新的数据
            if (realtime.has("pressure")) {
                currentWeatherData.setPressure(realtime.get("pressure").getAsString() + "hPa");
            }
            if (realtime.has("visibility")) {
                currentWeatherData.setVisibility(realtime.get("visibility").getAsString() + "km");
            }
            
            // 处理预报数据
            JsonArray future = result.getAsJsonArray("future");
            ArrayList<DayForecast> forecasts = new ArrayList<>();
            
            for (int i = 0; i < future.size(); i++) {
                JsonObject day = future.get(i).getAsJsonObject();
                String date = day.get("date").getAsString();
                String tempRange = day.get("temperature").getAsString();
                String weather = day.get("weather").getAsString();
                String windDir = day.get("direct").getAsString();
                
                // 解析温度范围
                String[] temps = tempRange.replace("℃", "").split("/");
                int minTemp = Integer.parseInt(temps[0]);
                int maxTemp = Integer.parseInt(temps[1]);
                
                // 创建预报对象
                DayForecast forecast = new DayForecast(
                    date,
                    weather,
                    minTemp,
                    maxTemp,
                    getWeatherIconByWid(day.getAsJsonObject("wid").get("day").getAsString()),
                    windDir,
                    "3-4级", // 由于API没有返回风力等级，使用默认值
                    50  // 由于API没有返回湿度，使用默认值
                );
                forecasts.add(forecast);
            }
            
            currentWeatherData.setForecasts(forecasts);
            
            // 设置今明两天温度
            if (!forecasts.isEmpty()) {
                currentWeatherData.setTodayTemp(forecasts.get(0).getMaxTemp() + "°/" + forecasts.get(0).getMinTemp() + "°");
                if (forecasts.size() > 1) {
                    currentWeatherData.setTomorrowTemp(forecasts.get(1).getMaxTemp() + "°/" + forecasts.get(1).getMinTemp() + "°");
                }
            }
            
            // 设置更新时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            currentWeatherData.setUpdateTime("更新时间：" + sdf.format(new Date()));
        }
    }

    private int getWeatherIconByWid(String code) {
        // 根据天气代码返回对应的图标资源ID
        switch (code) {
            case "00": // 晴
                return R.drawable.ic_clear;
            case "01": // 多云
                return R.drawable.ic_cloudy;
            case "02": // 阴
                return R.drawable.ic_cloudy;
            case "03": // 阵雨
            case "04": // 雷阵雨
            case "05": // 雷阵雨伴有冰雹
            case "06": // 雨夹雪
            case "07": // 小雨
            case "08": // 中雨
            case "09": // 大雨
            case "10": // 暴雨
            case "11": // 大暴雨
            case "12": // 特大暴雨
                return R.drawable.ic_rain;
            case "13": // 阵雪
            case "14": // 小雪
            case "15": // 中雪
            case "16": // 大雪
            case "17": // 暴雪
                return R.drawable.ic_snow;
            default:
                return R.drawable.ic_clear;
        }
    }

    public WeatherData getCurrentWeatherData() {
        return currentWeatherData;
    }
} 